package com.open.capacity.employee.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.open.capacity.common.annotation.ApiIdempotent;
import com.open.capacity.common.auth.details.LoginAppUser;
import com.open.capacity.common.exception.controller.ControllerException;
import com.open.capacity.common.exception.service.ServiceException;
import com.open.capacity.common.util.SysUserUtil;
import com.open.capacity.common.web.PageResult;
import com.open.capacity.common.web.Result;
import com.open.capacity.employee.model.EmployeeModel;
import com.open.capacity.employee.model.Information;
import com.open.capacity.employee.model.InformationModel;
import com.open.capacity.employee.service.EmpinformationService;
import com.open.capacity.log.annotation.LogAnnotation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/empinformation")
@Api(tags = "职工详情")
public class EmpinformationController {

    @Autowired
    private EmpinformationService empinformationService;

    /**
     * 当前登录面试人员 LoginAppUser
     *
     * @return
     * @throws ControllerException
     * @throws JsonProcessingException
     */
    @ApiOperation(value = "根据access_token当前登录面试人员")
    @GetMapping("/empinformation/current")
    @LogAnnotation(module = "employee-center", recordRequestParam = false)
    public LoginAppUser getLoginAppUser() throws ControllerException {
        try {
            LoginAppUser loginUser = SysUserUtil.getLoginAppUser();
            return loginUser;
        } catch (Exception e) {
            throw new ControllerException(e);
        }
    }


    @PreAuthorize("hasAuthority('user:get/empinformation/{id}')")
    @GetMapping("/empinformation/{id}")
    @LogAnnotation(module = "employee-center", recordRequestParam = false)
    public Information findUserById(@PathVariable Long id) throws ControllerException {
        try {
            return empinformationService.findById(id);
        } catch (ServiceException e) {
            throw new ControllerException(e);
        }
    }

    /**
     * 管理后台修改面试人员
     *
     * @param information
     * @throws JsonProcessingException
     */
    @PreAuthorize("hasAuthority('user:put/empinformation/me')")
    @PutMapping("/empinformation")
    @LogAnnotation(module = "employee-center", recordRequestParam = false)
    public void updateSysUser(@RequestBody Information information) throws ControllerException {
        try {
            empinformationService.updateSysUser(information);
        } catch (ServiceException e) {
            throw new ControllerException(e);
        }
    }


    /**
     * 面试人员查询
     * http://192.168.3.2:7000/empinformation?access_token=3b45d059-601b-4c63-85f9-9d77128ee94d&start=0&length=10
     *
     * @param params //  searchKey=username, searchValue=as
     * @return
     * @throws ControllerException
     */
    @PreAuthorize("hasAuthority('user:get/empinformation')")
    @ApiOperation(value = "面试人员查询列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页起始位置", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "limit", value = "分页结束位置", required = true, dataType = "Integer")
    })
    @GetMapping("/empinformation")
    @LogAnnotation(module = "employee-center", recordRequestParam = false)
    public PageResult<Information> findUsers(@RequestParam Map<String, Object> params) throws ControllerException {

        try {
            return empinformationService.findUsers(params);
        } catch (ServiceException e) {
            throw new ControllerException(e);
        }
    }

    /**
     * 图片上传
     */
    @PostMapping("/empinformation/picture")
    @LogAnnotation(module = "employee-center", recordRequestParam = false)
    public Result picture(@RequestParam("file") MultipartFile file) throws ControllerException {
        try {
            return empinformationService.picture(file);
        } catch (ServiceException e) {
            throw new ControllerException(e);
        }
    }

    /**
     * 修改面试人员状态
     *
     * @param params
     * @return
     * @throws ControllerException
     * @author gitgeek
     */
    @ApiOperation(value = "修改面试人员状态")
    @GetMapping("/empinformation/updateEnabled")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "面试人员id", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "enabled", value = "是否启用", required = true, dataType = "Boolean")
    })
    @LogAnnotation(module = "employee-center", recordRequestParam = false)
    @PreAuthorize("hasAnyAuthority('user:get/empinformation/updateEnabled' ,'user:put/empinformation/me')")
    public Result updateEnabled(@RequestParam Map<String, Object> params) throws ControllerException {
        try {
            Long id = MapUtils.getLong(params, "id");
            if (id == 1277137734524300032L) {
                return Result.failed("超级管理员不给予修改");
            }
            return empinformationService.updateEnabled(params);
        } catch (ServiceException e) {
            throw new ControllerException(e);
        }
    }


    /**
     * 新增or更新
     *
     * @param information
     * @return
     * @throws ControllerException
     */
    @PostMapping("/empinformation/saveOrUpdate")
    @PreAuthorize("hasAnyAuthority('user:post/empinformation/saveOrUpdate')")
    @LogAnnotation(module = "employee-center", recordRequestParam = false)
    public Result saveOrUpdate(@RequestBody Information information) throws ControllerException {
        try {
            return empinformationService.saveOrUpdate(information);
        } catch (ServiceException e) {
            throw new ControllerException(e);
        }
    }

    /**
     * 导出数据
     *
     * @return
     * @throws ControllerException
     */
    @PostMapping("/empinformation/exportUser")
    @PreAuthorize("hasAuthority('user:post/empinformation/exportUser')")
    public void exportUser(@RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) throws ControllerException {
        try {
            List<InformationModel> result = empinformationService.findAllUsers(params);
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=myExcel.xls");
            @Cleanup OutputStream ouputStream = null;
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("人员导出", "职工"),
                    InformationModel.class, result);
            ouputStream = response.getOutputStream();
            workbook.write(ouputStream);
        } catch (ServiceException e) {
            throw new ControllerException(e);
        } catch (IOException e) {
            throw new ControllerException(e);
        }

    }

    /**
     * 后台管理删除角色
     * delete /role/1
     *
     * @param id
     * @throws ControllerException
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "后台管理删除面试人员")
    @PreAuthorize("hasAuthority('user:post/users/saveOrUpdate')")
    @LogAnnotation(module = "employee-center", recordRequestParam = false)
    public Result deleteRole(@PathVariable Long id) throws ControllerException {
        try {
            if (id == 1277137734524300032L) {
                return Result.failed("管理员不可以删除");
            }
            empinformationService.deleteUser(id);
            return Result.succeed("操作成功");
        } catch (Exception e) {
            throw new ControllerException(e);
        }
    }

    /**
     * 测试幂等接口
     *
     * @param information
     * @return
     * @throws ControllerException
     */
    @PostMapping("/empinformation/save")
    @ApiIdempotent
    public Result save(@RequestBody Information information) throws ControllerException {
        try {
            return empinformationService.saveOrUpdate(information);
        } catch (ServiceException e) {
            log.error("执行" + this.getClass().getSimpleName() + ":" + new Exception().getStackTrace()[0].getMethodName());
            throw new ControllerException(e);
        }
    }


}

